﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace LectorHuellaC
{
    public partial class FormProductosSucursal : Form
    {
        log4net.ILog logger;

        int id_empresa = Convert.ToInt32(Settings1.Default.id_empresa);
        string IdSucursal = Settings1.Default.IdSucursal;
        cls_category cls_category = new cls_category();

        Controllers.cls_productos_sucursal _cls_productos_sucursal = new Controllers.cls_productos_sucursal();
        cls_productos cls_product = new cls_productos();
        Controllers.cls_sucursales _sucursales = new Controllers.cls_sucursales();
        public FormProductosSucursal()
        {
            log4net.Config.XmlConfigurator.Configure();
            logger = log4net.LogManager.GetLogger(typeof(Program));
            InitializeComponent();
            pintarProductosSucursal();
            getProducts();
            getSucursales();
            getCategories();
            cbproducts.Enabled = false;
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Dispose();
            Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int product_id = 0;
            try
            {
                if (txtpcompra.Text.Trim().Equals(""))
                {
                    MessageBox.Show("Campo Precio compra no puede estar vacion", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
              
                if (txtpventa.Text.Trim().Equals(""))
                {
                    MessageBox.Show("Campo precio venta no puede estar vacion", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                 if (txtpexisten.Text.Trim().Equals(""))
                {
                    MessageBox.Show("Campo existencia no puede estar vacion", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                 int product_sucursal_id = 0;
                if (!chknuevoproducto.Checked)
                {
                    product_sucursal_id = Convert.ToInt32(PrintCellRowAndCol());

                }
                
                product_id = Convert.ToInt32(cbproducts.SelectedValue);
                int id_sucursal = Convert.ToInt32(cbSucursal.SelectedValue);
                double price_buy = Convert.ToDouble(txtpcompra.Text);
                double price_sale = Convert.ToDouble(txtpventa.Text);
                int existencia = Convert.ToInt32(txtpexisten.Text);



                bool resp = _cls_productos_sucursal.insertarActualizarProductosSucursal(product_sucursal_id,product_id, id_sucursal, price_buy, price_sale, existencia);
                if (resp)
                {
                    MessageBox.Show("Se realizo la insercion", "Insercion productos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    pintarProductosSucursal();
                    limpiarControles();
                }
                else
                {
                    MessageBox.Show("Se ha presentado un problema", "Insercion productos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    limpiarControles();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error" + ex.Message);
            }
        }

        private void limpiarControles()
        {
            txtpcompra.Text = "";
            txtpexisten.Text = "";
            txtpventa.Text = "";
        }

        public void pintarProductosSucursal()
        {
            dataGridView1.DataSource = _cls_productos_sucursal.getAllProductsSucursal();
        }

        private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
        {
            string search = "";
            int sucursal_id = Convert.ToInt32(cbSucursal.SelectedValue);
            int category_id = Convert.ToInt32(cbcategoria.SelectedValue);
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                search = textBox4.Text;
                dataGridView1.DataSource = _cls_productos_sucursal.getProductSucursalByCriteria(search, sucursal_id,category_id);
            }
        }

        public void getCategories()
        {
            DataTable categories = cls_category.getCategories();

            ArrayList arreglo = new ArrayList();
            foreach (DataRow categoryrow in categories.Rows)
            {
                arreglo.Add(new Entidades.Categories(Convert.ToInt32(categoryrow["category_id"].ToString()), categoryrow["category_name"].ToString()));
            }
            cbcategoria.DataSource = arreglo;
            cbcategoria.DisplayMember = "_category_name";
            cbcategoria.ValueMember = "_category_id";
            cbcategoria_SelectedIndexChanged(cbcategoria, System.EventArgs.Empty);
        }

        private void cbcategoria_SelectedIndexChanged(ComboBox cbcategoria, EventArgs eventArgs)
        {
          
        }

        public void getProducts()
        {
            DataTable categories = cls_product.getProductInfo(0, 0);

            ArrayList arreglo = new ArrayList();
            foreach (DataRow categoryrow in categories.Rows)
            {
                arreglo.Add(new Entidades.Products(Convert.ToInt32(categoryrow["product_id"].ToString()), categoryrow["product_name"].ToString()));
            }
            cbproducts.DataSource = arreglo;
            cbproducts.DisplayMember = "product_name";
            cbproducts.ValueMember = "product_id";
            cbproducts_SelectedIndexChanged(cbproducts, System.EventArgs.Empty);
        }

        private void cbproducts_SelectedIndexChanged(ComboBox cbproducts, EventArgs eventArgs)
        {
            
        }

        public void getSucursales()
        {
            int id_empresa = this.id_empresa;
            cbSucursal.DataSource = null;
            cbSucursal.Items.Clear();
            ConectaBD conBD = new ConectaBD();


            DataTable datasurcusal = _sucursales.getAllBranchs(id_empresa);

           

            ArrayList arreglo = new ArrayList();
            foreach (DataRow dr2 in datasurcusal.Rows)
            {
                arreglo.Add(new Entidades.Sucursales(Convert.ToInt32(dr2["id_sucursal"]), dr2["sc_nombre"].ToString()));
            }

            cbSucursal.DataSource = arreglo;
            cbSucursal.DisplayMember = "sc_nombre";
            cbSucursal.ValueMember = "id_sucursal";
            //cbSucursal.SelectedValue = (Convert.ToString(datasurcusal_selected.Tables[0].Rows[0]["IdSucursal"]));

           

            cbSucursal_SelectedIndexChanged(cbSucursal, System.EventArgs.Empty);
        }

        private void cbSucursal_SelectedIndexChanged(ComboBox cbSucursal, EventArgs eventArgs)
        {
          
        }

        public int PrintCellRowAndCol()
        {
            // Prints the value of the cell through the DataTable.
            DataTable myTable;
            // Assumes the DataGrid is bound to a DataTable.
            myTable = (DataTable)dataGridView1.DataSource;
            int id_producto_sucursal = 0;
            if (dataGridView1.Rows.Count != 0)
            {
                DataGridViewCell myCell;
                myCell = dataGridView1.CurrentCell;
                if (myCell != null)
                {
                    if (myCell.Selected)
                    {
                        DataRow values = myTable.Rows[myCell.RowIndex];
                        id_producto_sucursal = Convert.ToInt32(values[0]);
                    }
                }
            }
            return id_producto_sucursal;
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow row = dataGridView1.CurrentRow;

            if (!string.IsNullOrEmpty(Convert.ToString(row.Cells["product_id"].Value)))
            {

                DataTable myTable;
                myTable = (DataTable)dataGridView1.DataSource;

                DataGridViewCell myCell;
                myCell = dataGridView1.CurrentCell;


                DataRow values = myTable.Rows[myCell.RowIndex];

                txtpcompra.Text = Convert.ToString(values["product_price_buy"]);
                txtpventa.Text = Convert.ToString(values["product_price_sale"]);
                txtpexisten.Text = Convert.ToString(values["product_existence"]);
                cbproducts.Enabled = false;
            }
            else
            {
                cbproducts.Enabled = true;
                limpiarControles();
            }
        }

        private void chknuevoproducto_CheckedChanged(object sender, EventArgs e)
        {
            if (chknuevoproducto.Checked)
            {
                cbproducts.Enabled = true;
            }
            else
            {
                cbproducts.Enabled = false;
            }
        }
    }
}
